package iot

import (
	"fmt"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"

	"github.com/fakeyanss/jt808-server-go/global"
	"github.com/fakeyanss/jt808-server-go/internal/iot/model"
)

func mustInitPgsql() *gorm.DB {
	p := global.Config.Pgsql
	dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v %v", p.Host, p.Username, p.Password, p.Dbname, p.Port, p.Config)

	pgsqlConfig := postgres.Config{
		DSN:                  dsn, // DSN data source name
		PreferSimpleProtocol: false,
	}

	db, err := gorm.Open(postgres.New(pgsqlConfig), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(p.MaxIdleConns)
	sqlDB.SetMaxOpenConns(p.MaxOpenConns)

	err = db.AutoMigrate(
		model.Location{},
	)
	if err != nil {
		panic(err)
	}

	return db
}
